package com.echat.config.security.authention;

import com.echat.config.security.enums.LoginType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author chentl
 * @version V1.0
 * @Project MyAuthenticationSuccessHandler
 * @Title MyAuthenticationSuccessHandler.java
 * @Description 成功的权限认证处理器
 * @Package com.echat.config.security.authention
 * @date 2019/6/8 23:33
 * @Copyright: 上海顺益信息科技有限公司 All rights reserved.
 */
@Component
@Slf4j
public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {


    @Value("auth.security.browser.loginType")
    private String loginType;

    /**
     * json 转换工具类
     */
    private ObjectMapper objectMapper;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        logger.info("登录成功");

        //判断是json 格式返回 还是 view 格式返回
        if (LoginType.JSON.equals(loginType)) {
            //将 authention 信息打包成json格式返回
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(authentication));
        } else {
            //返回view
            super.onAuthenticationSuccess(request, response, authentication);
        }

    }
}
